from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from .ser import *
from utils.comm import get_redis
import random
# Create your views here.


#新闻
class Nuws_API(APIView):
    def post(self,request):
        ser = Nuws_Ser(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code":200})
        else:
            print(ser.errors)
            return Response({"code": 10010})

    def get(self,request):
        id = request.GET.get("id")
        if not id:
            n = Nuws.objects.all()
            cpage = request.GET.get("cpage")
            pag = Paginator(n,2)
            tpage = pag.page(cpage)
            num = pag.num_pages
            ser = Nuws_Ser(tpage,many=True)
            return Response({"code":200,"list":ser.data,'num':num})
        else:
            n = Nuws.objects.filter(id = id).first()
            ser = Nuws_Ser(n)
            return Response({"code":200,"list":ser.data})

#广告
class Advertising_API(APIView):
    def post(self,request):
        ser = Advertising_Ser(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code":200})
        else:
            print(ser.errors)
            return Response({"code": 10010})

    def get(self,request):
        n = Advertising.objects.all()
        cpage = request.GET.get("cpage")
        pag = Paginator(n, 2)
        tpage = pag.page(cpage)
        num = pag.num_pages
        ser = Advertising_Ser(tpage, many=True)
        return Response({"code": 200, "list": ser.data, 'num': num})

from ronglian_sms_sdk import SmsSDK
import json
accId = '8aaf07087bc82708017bf7c9eb000e8c'
accToken = '643c8691dee541f19a620cd8e21fd7c5'
appId = '8aaf07087bc82708017bf7c9ebdd0e93'

from utils.comm import send_message
import random

class Zhc(APIView):
    def get(self,request):
        s = send_message('15309518018',"你好",1)
        print(s)
        return Response({"code":200})

import re

class RegAPI(APIView):

    def post(self,request):
    #注册账号
        #是否为空
        username = request.data.get('username')
        if not username:
            return Response({"code":10010})
        #正则
        reg = re.match('\w{5,12}$',username)
        if not reg:
            return Response({"code":10011})
        #是否唯一
        user = User.objects.filter(username=username).first()
        if user:
            return Response({"code":10012})
    #注册手机号
        mobile = request.data.get('mobile')
        if not mobile:
            return Response({"code": 10013})
        # 正则
        regmo = re.match('^1[3-9]\d{9}$', mobile)
        if not regmo:
            return Response({"code": 10014})
        # 是否唯一
        user = User.objects.filter(mobile=mobile).first()
        if user:
            return Response({"code": 10015})
    #注册密码
        pas = request.data.get("password")
        if not pas:
            return Response({"code": 10016})
        preg = re.match('^\w{8,20}$',pas)
        if not preg:
            return Response({"code": 10017})
    # 判断确认密码
        que_pas = request.data.get("query_password")
        if que_pas != pas:
            return Response({"code": 10018})
    #判断短信验证码
        dxyzm = request.data.get('dxyzm')
        conn = get_redis()
        c = conn.get(mobile)
        if not dxyzm:
            return Response({"code":10019})
        if c:
            c = str(c,encoding="utf8")
        if c != dxyzm:
            return Response({"code":10020})

        return Response({"code":200})




#发信息

class SedSms(APIView):
    def post(self,request):
        mobile = request.data.get('mobile')
        uuid = request.data.get("uuid")
        txyzm = request.data.get("txyzm")
        conn = get_redis()
        d = conn.get(uuid)
        code = random.randint(100000,999999)
        if d:
            d = str(d,encoding="utf8")
        if txyzm.lower() == d.lower():
            res = send_message(mobile,str(code),1)
            codes = 10010
            if res:
                codes=200
                conn = get_redis()
                conn.setex(mobile,60,code)
            return Response({"code":codes})
        return Response({"code":20111})
from p5 import settings
import jwt
from django.contrib.auth.hashers import check_password,make_password
class add_urser(APIView):
    def post(self,request):
        username = request.data.get("username")
        request.data['password'] = make_password(request.data.get("password"))
        ser = User_Ser(data=request.data)
        if ser.is_valid():
            ser.save()
            u = User.objects.filter(username=username).first()
            token = jwt.encode({'data': {'username': username}}, settings.SECRET_KEY, algorithm='HS256')
            return Response({"code":200,'token':token,"userid":u.id})
        else:
            print(ser.errors)
            return Response({"code":10010})
from django.db.models import Q

class Login_API(APIView):
    def post(self,request):
        pas = request.data.get("password")
        use = request.data.get("username")
        u = User.objects.filter(Q(username=use)|Q(mobile = use)).first()
        if u:
            if check_password(pas,u.password):
                token = jwt.encode({'data': {'username': use}}, settings.SECRET_KEY, algorithm='HS256')
                return Response({"code":200,"token":token,'userid':u.id})
        return Response({"code":10010})



class Address_API(APIView):
    def post(self,request):
        ser = Addresss_Ser(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code":200})
        else:
            print(ser.errors)
            return Response({"code":10010})

    def get(self,request):
        pid = request.GET.get("pid")
        if not pid:
            areas = Area.objects.filter(parent_id__isnull=True).all()
        else:
            areas = Area.objects.filter(parent_id=pid).all()
        ser = Area_Ser(areas,many=True)
        return Response({"code":200,'list':ser.data})

class Show_Address(APIView):
    def get(self,request):
        userid = request.GET.get("userid")
        a = Address.objects.filter(user_id=userid).all()
        ser = Address_Ser(a,many=True)
        return Response({"code":200,"list":ser.data})

    def put(self,request):
        id = request.GET.get("id")
        a = Address.objects.filter(id=id).first()
        Address.objects.filter(user_id=a.user_id,is_default=1).update(is_default=0)
        a.is_default = 1
        a.save()
        return Response({"code":200})









#链接redis
class Redis(APIView):
    def get(self,request):
        conn = get_redis()
        conn.setex('name',10,'zzz')
        name = conn.get('name')
        return Response(name)

from utils.captcha.captcha import captcha

class ImageCodeAPIView(APIView):
    def get(self,request):
        uuid = request.GET.get("uuid")
        name,text,pic = captcha.generate_captcha()
        redis_con = get_redis()
        redis_con.setex(uuid,60,text)
        return HttpResponse(pic, content_type='image/jpg')




